<template>
  <div id="checkapproveDiv">
    <Breadcrumb content="申请审核" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-form :data="searchForm" class="searchform form-input-m">
            <vxe-form-item title="申请日期[起]">
              <template #default="{ data }">
                <el-date-picker v-model="data.reqTimeBegin" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="申请日期[起]" :shortcuts="shortcuts" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="申请日期[止]">
              <template #default="{ data }">
                <el-date-picker v-model="data.reqTimeEnd" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="申请日期[止]" :shortcuts="shortcuts" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="送检单位">
              <vxe-select v-model="searchForm.companyCode" :filterable="true" @change="companyCodeChangeEvent" clearable transfer>
                <vxe-option v-for="orderSObj in inspectCompanyList" :key="orderSObj.id" :value="orderSObj.companyCode" :label="orderSObj.companyName"></vxe-option>
              </vxe-select>
            </vxe-form-item>
            <vxe-form-item title="样本条码">
              <vxe-input v-model="searchForm.reqNo" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findReqMainList" @keyup="keyupEnter" @search-click="findReqMainList()"></vxe-input>
            </vxe-form-item>
            <vxe-form-item title="申请状态">
              <vxe-select v-model="searchForm.state" placeholder="申请状态" class-name="width-100-percentage" @change="stateCodeChangeEvent">
                <vxe-option v-for="(item, index) in reqStateList" :key="index" :label="item.name" :value="item.code"></vxe-option>
              </vxe-select>
            </vxe-form-item>
            <vxe-form-item>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="查询" :loading="mLoading" @click="findReqMainList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-send" content="审核" @click="reqMainApprove"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-send-fill" content="批量审核" @click="reqMainBatchApprove"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-repeat" content="审核解除" @click="reqMainCancelApprove"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="申请修改" @click="editReqMainDialog"></vxe-button>
            </vxe-form-item>
          </vxe-form>
        </template>
      </vxe-toolbar>
      <Splitpanes>
        <Pane size="70">

          <div class="tableBox">
            <vxe-table ref="reqMainTableRef" :data="reqMainList" :loading="mLoading" @current-change="reqMainRowClick" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
              <vxe-column field="reqNo" title="样本条码" width="150"> </vxe-column>
              <vxe-column field="stateNa" title="状态" width="80"></vxe-column>
              <vxe-column field="inspectCompanyName" title="送检单位" width="100"></vxe-column>
              <vxe-column field="patNo" title="病人代号" width="100"></vxe-column>
              <vxe-column field="patNa" title="姓名" width="100"></vxe-column>
              <vxe-column field="sexNa" title="性别" width="100"></vxe-column>
              <vxe-column field="ageStr" title="年龄" width="100"></vxe-column>
              <vxe-column field="sampleTypeNa" title="标本类型" width="100"></vxe-column>
              <vxe-column field="reqDeptNa" title="科室" width="100"></vxe-column>
              <vxe-column field="bedNo" title="床号" width="100"></vxe-column>
              <vxe-column field="reqTime" title="申请时间" width="100"></vxe-column>
              <vxe-column field="reqDoctorNa" title="申请医师" width="100"></vxe-column>
              <vxe-column field="samplingTime" title="采样时间" width="100"></vxe-column>
              <vxe-column field="samplingDoctorNa" title="采样医师" width="100"></vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="30">
          <div class="tableBoBox">
            <vxe-table ref="reqDetailTableRef" :data="reqDetailList" :loading="dLoading" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" width="24" fixed="left"></vxe-column>
              <vxe-column field="feeCode" title="收费项目代号" width="90"></vxe-column>
              <vxe-column field="feeName" title="收费项目名称" min-width="120"></vxe-column>
              <vxe-column field="price" title="单价" width="100"></vxe-column>
              <vxe-column field="amount" title="数量" width="100"></vxe-column>
              <vxe-column field="costs" title="金额" width="100"></vxe-column>
            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>

  <vxe-modal v-model="reqMainFormVisiable" width="60vw" show-footer :mask="false">
    <template #title>
      <span class="text-bold">申请修改</span>
    </template>
    <template #default>
      <div class="tableBody" style="height: 700px">
        <Splitpanes class="SplitpanesAll" :dbl-click-splitter="false">
          <Pane size="30">
            <div class="padding-lr-xs">
              <el-scrollbar>
                <vxe-form :data="reqMainForm" ref="wlconfigpatsettingForm" class-name="form-pat-info margin-bottom form-size-auto" className="" title-align="left" title-width="60">
                  <vxe-form-item title="样本条码" span="24" field="reqNo">
                    <template #default="{ data }">
                      <vxe-input ref="reqNoInput" v-model="data.reqNo" disabled v-enterNextInput class="enterNextInputFlag" clearable></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="送检单位" span="24" field="patType">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="pdownCompany" :url="'/lab/inspectCompany/findInspectCompanyList'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'companyName', title: '名称' },
                          { field: 'companyCode', title: '编码' }
                        ]" :aimKeys="[
                          { aimKey: 'inspectCompanyName', rowKey: 'companyName' },
                          { aimKey: 'inspectCompany', rowKey: 'companyCode' }
                        ]" :displayTexts="['inspectCompanyName']" :displayTextObj="data.inspectCompanyName ? data.inspectCompanyName : ''" :dataObj="null" />

                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="病人代号" span="24" field="reqNo">
                    <template #default="{ data }">
                      <vxe-input ref="patNoInput" v-model="data.patNo" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable></vxe-input>
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="病人类型" span="24" field="patType">
                    <template #default="{ data }">
                      <VxeDictSelection v-enterNextInput :isChild="false" :tableColumn="[
                        { field: 'code', title: '编码', width: `60px` },
                        { field: 'name', title: '名称', minWidth: `80px` }
                      ]" :url="`/api/sys/basDictDetail/findDictDetailList`" ref="patTypeDictpdown" :displayTextObj="data.patTypeNa ? data.patTypeNa : ''" @confirmClick="SelectRowClick" :aimKeys="[
                        { aimKey: 'patTypeNa', rowKey: 'name' },
                        { aimKey: 'patType', rowKey: 'code' }
                      ]" :dataObj="{ code: 'PATTYPE' }"></VxeDictSelection>

                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="姓名" span="24" field="reqNo">
                    <template #default="{ data }">
                      <vxe-input v-model="data.patNa" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable></vxe-input>
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="性别" span="24" field="sex">
                    <template #default="{ data }">

                      <VxeDictSelection ref="sexDictpdown" v-enterNextInput :isChild="false" :tableColumn="[
                        { field: 'code', title: '编码', width: `60px` },
                        { field: 'name', title: '名称', minWidth: `80px` }
                      ]" :url="`/api/sys/basDictDetail/findDictDetailList`" :displayTextObj="data.sexNa ? data.sexNa : ''" @confirmClick="SelectRowClick" :aimKeys="[
                          { aimKey: 'sexNa', rowKey: 'name' },
                          { aimKey: 'sex', rowKey: 'code' }
                        ]" :dataObj="{ code: 'sex' }"></VxeDictSelection>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="出生日期" span="24" field="birthDay">
                    <template #default="{ data }">
                      <vxe-input v-model="data.birthDay" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" type="datetime" v-enterNextInput class="enterNextInputFlag" style="width: 100%" clearable transfer></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="年龄" span="24" field="sex">
                    <template #default="{ data }">
                      <AgeComp class="enterNextInputFlag" :ageObj="{ age: data.age, ageUnit: data.ageUnit }" @ageChange="ageChange" />
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="联系电话" span="24" field="telNo">
                    <template #default="{ data }">
                      <vxe-input v-model="data.telNo" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="证件号码" span="24" field="idNo">
                    <template #default="{ data }">
                      <vxe-input v-model="data.idNo" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="标本类型" span="24" field="sampleType">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="sampleTypePdown" :url="'/api/lab/labSampleType/findSampleTypeList'" @confirmClick="SelectRowClick" :tableColumn="[
                         { type: 'seq', title: '#', width: '30px' },
                          { field: 'sampleTypeName', title: '名称' },
                          { field: 'sampleTypeCode', title: '编码' }
                        ]" :aimKeys="[
                         { aimKey: 'sampleTypeNa', rowKey: 'sampleTypeName' },
                          { aimKey: 'sampleType', rowKey: 'sampleTypeCode' }
                        ]" :displayTexts="['sampleTypeNa']" :displayTextObj="data.sampleTypeNa ? data.sampleTypeNa : ''" :dataObj="null" />

                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="检验目的" span="24" field="reqPurpose">
                    <template #default="{ data }">
                      <vxe-textarea v-model="data.reqPurpose" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable></vxe-textarea>
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="科室" span="24" field="reqDept">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="reqDeptDdown" :url="'/api/sys/findDepartmentListbyCurrentUserOrg'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'name', title: '名称' },
                          { field: 'code', title: '编码' }
                        ]" :aimKeys="[
                          { aimKey: 'reqDeptNa', rowKey: 'name' },
                          { aimKey: 'reqDept', rowKey: 'code' }
                        ]" :displayTexts="['reqDeptNa']" :displayTextObj="data.reqDeptNa ? data.reqDeptNa : ''" :dataObj="null" />
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="床号" span="24" field="bedNo">
                    <template #default="{ data }">
                      <vxe-input v-model="data.bedNo" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable></vxe-input>
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="申请时间" span="24" field="reqTime">
                    <template #default="{ data }">
                      <vxe-input v-model="data.reqTime" type="datetime" v-enterNextInput class="enterNextInputFlag" style="width: 100%" clearable transfer></vxe-input>
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="申请医师" span="24" field="reqDoctor">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="reqDoctorPdown" :url="'/api/sys/hisEmployee/finAllHisEmployeeList'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'name', title: '名称' },
                          { field: 'code', title: '编码' }
                        ]" :aimKeys="[
                          { aimKey: 'reqDoctorNa', rowKey: 'name' },
                          { aimKey: 'reqDoctor', rowKey: 'code' }
                        ]" :displayTexts="['reqDoctorNa']" :displayTextObj="data.reqDoctorNa ? data.reqDoctorNa : ''" :dataObj="null" />
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="采样时间" span="24" field="samplingTime">
                    <template #default="{ data }">
                      <vxe-input v-model="data.samplingTime" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" type="datetime" v-enterNextInput class="enterNextInputFlag" style="width: 100%" clearable transfer></vxe-input>
                    </template>
                  </vxe-form-item>

                  <vxe-form-item title="采样医师" span="24" field="samplingDoctor">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="samplingDoctorPdown" :url="'/api/user/getUserInfoList'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'realname', title: '名称' },
                          { field: 'username', title: '编码' }
                        ]" :aimKeys="[
                           { aimKey: 'samplingDoctorNa', rowKey: 'realname' },
                          { aimKey: 'samplingDoctor', rowKey: 'username' }
                        ]" :displayTexts="['samplingDoctorNa']" :displayTextObj="data.samplingDoctorNa ? data.samplingDoctorNa : ''" :dataObj="null" />
                    </template>
                  </vxe-form-item>

                </vxe-form>
              </el-scrollbar>
            </div>
          </Pane>
          <Pane size="70">
            <Splitpanes horizontal class="horizontalLine">
              <Pane size="60">
                <vxe-toolbar perfect>
                  <template #buttons>
                    <span class="padding-lr-xs">
                      <vxe-button type="text" content="删除" class-name="padding-lr-xs" class="button-red padding-lr-xs" @click="deleteReqDetailList" />
                    </span>
                  </template>
                </vxe-toolbar>
                <div class="tableMoSaBox">
                  <vxe-table ref="labReqdetailTableRef" :data="reqMainForm.labReqdetailList" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                    <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
                    <vxe-column type="seq" width="24" fixed="left"></vxe-column>
                    <vxe-column field="feeCode" title="收费项目代号" width="90"></vxe-column>
                    <vxe-column field="feeName" title="收费项目名称" min-width="120"></vxe-column>
                    <vxe-column field="price" title="单价" width="100"></vxe-column>
                    <vxe-column field="amount" title="数量" width="100"></vxe-column>
                    <vxe-column field="costs" title="金额" width="80px" align="right"></vxe-column>

                  </vxe-table>
                </div>
              </Pane>
              <Pane size="40">
                <Splitpanes class="Splitpanes" :dbl-click-splitter="false">
                  <Pane size="30">
                    <vxe-table ref="barCodeTypeTable" :data="barCodeList" :loading="showLoading" @current-change="barCodeRowClick" border class="mytable-scrollbar" show-header-overflow show-overflow align="center" :row-config="{ isCurrent: true, isHover: true }">
                      <vxe-column field="color" title="颜色" width="75" :edit-render="{ autofocus: '.vxe-input--inner' }">
                        <template #default="{ row }">
                          <el-tag class="margin-lr-xs" :style="{ background: row.color ? row.color : '' }" v-if="row.color"></el-tag>
                        </template>
                      </vxe-column>
                      <vxe-column field="barcodeNa" title="分类名称"> </vxe-column>
                    </vxe-table>
                  </Pane>
                  <Pane size="70">
                    <vxe-table ref="feeItemTableRef" :data="feeItemList" :loading="feeLoading" @checkbox-change="feeItemChangeRow" height="auto" class="mytable-scrollbar" border="inner" align="center" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                      <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
                      <vxe-column type="seq" title="序号" width="30"></vxe-column>
                      <vxe-column field="feeCode" title="项目编号" width="70" align="left"></vxe-column>
                      <vxe-column field="feeName" title="项目名称" min-width="160" align="left"></vxe-column>
                      <vxe-column field="price" title="单价" width="70"></vxe-column>
                    </vxe-table>
                  </Pane>
                </Splitpanes>
              </Pane>
            </Splitpanes>
          </Pane>
        </Splitpanes>
      </div>
    </template>

    <template #footer>
      <vxe-button type="text" class="button-white margin-right" @click="cancelReqMainEvent">关闭</vxe-button>
      <vxe-button type="text" class="button-blue" @click="saveReqMainForm">保存</vxe-button>
    </template>
  </vxe-modal>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, ObjectDirective } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { IsEmpty, formatDateTime, autoIncrementNumber, sortByField } from '@/utils/common';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import { AppStore } from '@/stores/store'; //'../../../stores/store';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import VxeDictSelection from '@/components/VxeDictSelection.vue';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';
import AgeComp from '@/components/AgeComp.vue';
let store = AppStore();
const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return date;
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return date;
    }
  }
];

let searchForm = reactive({
  searchValue: '',
  companyCode: '',
  reqNo: '',
  state: '10',
  reqTimeBegin: formatDateTime(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd 00:00:00'),
  reqTimeEnd: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59')
});
let reqMainForm: any = reactive({
  id: null,
  reqNo: '',
  state: '',
  stateNa: '',
  inspectCompany: '',
  inspectCompanyName: '',
  checkCompany: '',
  checkCompanyName: '',
  patType: '',
  patTypeNa: '',
  patNo: '',
  patNa: '',
  sex: '',
  sexNa: '',
  birthDay: '',
  age: null,
  ageUnit: '',
  ageStr: '',
  telNo: '',
  sampleType: '',
  sampleTypeNa: '',
  idNo: '',
  reqPurpose: '',
  bedNo: '',
  reqDept: '',
  reqDeptNa: '',
  reqDoctor: '',
  reqDoctorNa: '',
  reqTime: '',
  samplingDoctor: '',
  samplingDoctorNa: '',
  samplingTime: '',
  orgId: '',
  labReqdetailList: []
});
let inspectCompanyList: any = reactive([]);
let feeLoading = ref(false); //刷新+表格加载

// 页面加载时更新报告单元/字典
onMounted(async () => {
  findInspectCompanyList();
  getBarCodeList();
  await findReqMainList();
});

let mLoading = ref(false); //刷新加载状态
let dLoading = ref(false); //刷新加载状态
let showLoading = ref(false); //刷新加载状态
let reqMainList: any = reactive([]);
let reqDetailList: any = reactive([]);

let barCodeList: any = reactive([]);

let reqStateList: any = reactive([
  { code: '10', name: '申请' },
  { code: '85', name: '已审核' }
]);

let sltReqMain: any = reactive({});

async function findReqMainList() {
  mLoading.value = true;
  reqMainList.length = 0; //放入数据前清空数据
  const url = '/lab/reqMain/findReqMainList';
  await proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchForm.searchValue,
        companyCode: searchForm.companyCode,
        reqNo: searchForm.reqNo,
        state: searchForm.state,
        reqTimeBegin: searchForm.reqTimeBegin,
        reqTimeEnd: searchForm.reqTimeEnd
      }
    })
    .then((res: any) => {
      reqMainList.push(...res.data);
      if (reqMainList.length == 0) {
        sltReqMain = {};
        reqDetailList.length = 0;
      } else {
        const kn = reqMainList.find((k: any) => k.id == sltReqMain.id);
        if (IsEmpty(kn)) {
          reqMainRowClick({ row: reqMainList[0] }); //默认选中第一条数据
        } else {
          reqMainRowClick({ row: kn }); //默认选中第一条数据
        }
      }

      mLoading.value = false;
    })
    .catch((err: any) => {
      mLoading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function reqMainRowClick({ row }: any) {
  if (IsEmpty(row)) {
    sltReqMain = {};
    reqDetailList.length = 0;
  } else {
    (proxy.$refs.reqMainTableRef as any).setCurrentRow(row);
    sltReqMain = row;
    findReqDetailList();
  }
}

function findReqDetailList() {
  reqDetailList.length = 0;
  dLoading.value = true;
  const url = '/api/reqdetail/getDetailByBarcode';
  proxy.$http
    .get(url, { params: { reqNo: sltReqMain.reqNo } })
    .then((res: any) => {
      reqDetailList.length = 0;
      reqDetailList.push(...res.data);

      dLoading.value = false;
    })
    .catch((err: any) => {
      dLoading.value = false;
      proxy.$alert(err, '提示');
    });
}
function reqMainApprove() {
  if (IsEmpty(sltReqMain)) {
    VxeMessage('请选择审核数据', VxeNotifyType.info);
  } else {
    if (sltReqMain.state != '10') {
      VxeMessage('数据已审核', VxeNotifyType.info);
    } else {
      proxy
        .$confirm('确定审核？', '提示', {
          cancelButtonClass: 'cancel-button',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          let sltreqMains = [];
          sltreqMains.push(sltReqMain);
          const data = { reqMainList: sltreqMains };
          const url = '/lab/reqMain/batchReqMainApprove';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findReqMainList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        })
        .catch((err: any) => {
          // VxeMessage(err, VxeNotifyType.error);
        });
    }
  }
}

function reqMainBatchApprove() {
  const sltReqMains = (proxy.$refs.reqMainTableRef as any).getCheckboxRecords();
  if (!(sltReqMains.length > 0)) {
    VxeMessage('请勾选要审核的单据', VxeNotifyType.info);
  } else {
    let cantCheckList = sltReqMains.filter((x: any) => x.state != '10');
    if (cantCheckList.length > 0) {
      VxeMessage('请选择未审核的单据', VxeNotifyType.info);
    } else {
      proxy
        .$confirm('确定批量审核？', '提示', {
          cancelButtonClass: 'cancel-button',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          const data = { reqMainList: sltReqMains };
          const url = '/lab/reqMain/batchReqMainApprove';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findReqMainList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        })
        .catch((err: any) => {
          // VxeMessage(err, VxeNotifyType.error);
        });
    }
  }
}

function reqMainCancelApprove() {
  console.log(sltReqMain);
  if (IsEmpty(sltReqMain)) {
    VxeMessage('请选择审核解除数据', VxeNotifyType.info);
  } else {
    if (sltReqMain.state != '85') {
      VxeMessage('数据未核对', VxeNotifyType.info);
    } else {
      proxy
        .$confirm('确定审核解除？', '提示', {
          cancelButtonClass: 'cancel-button',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          let sltreqMains = [];
          sltreqMains.push(sltReqMain);
          const data = { reqMainList: sltreqMains };
          const url = '/lab/reqMain/cancelReqMainApprove';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findReqMainList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        })
        .catch((err: any) => {
          // VxeMessage(err, VxeNotifyType.error);
        });
    }
  }
}
let reqMainFormVisiable = ref(false);

function editReqMainDialog() {
  if (IsEmpty(sltReqMain)) {
    VxeMessage('请选择修改的数据', VxeNotifyType.info);
  } else {
    if (sltReqMain.state != '10') {
      VxeMessage('数据已审核', VxeNotifyType.info);
    } else {
      setReqMainForm(sltReqMain);
      reqMainFormVisiable.value = true;

      proxy.$nextTick(() => {
        if (barCodeList.length > 0) {
          barCodeRowClick({ row: barCodeList[0] });
        }
      });
    }
  }
}

function setReqMainForm(row: any) {
  Object.assign(reqMainForm, row);
  reqMainForm.labReqdetailList = [];
  reqMainForm.labReqdetailList.push(...reqDetailList);
}
function clearReqMainForm() {
  for (const key in reqMainForm) {
    if (Object.prototype.hasOwnProperty.call(reqMainForm, key)) {
      reqMainForm[key] = '';
    }
  }
}
function cancelReqMainEvent() {
  clearReqMainForm();
  reqMainFormVisiable.value = false;
}
async function findInspectCompanyList() {
  const url = '/lab/inspectCompany/findInspectCompanyList';
  await proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      if (res.status.code === 1) {
        inspectCompanyList.push(...res.data);
      }
    })
    .catch((err: any) => {
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}

function getBarCodeList() {
  barCodeList.length = 0;
  showLoading.value = true;
  const url = '/api/lab/labbarcodetype/findBarCodeTypeList';
  let obj = {
    keyWords: ''
  };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      barCodeList.push(...sortByField(res.data, 'barcodeNo', 'asc'));

      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showLoading.value = false;
    });
}
let selevctBarCodeRow: any = reactive({});

function barCodeRowClick({ row }: any) {
  (proxy.$refs.barCodeTypeTable as any).setCurrentRow(row);
  selevctBarCodeRow = row;

  findFeeItemVsBarCodeList();
}
let feeItemList = reactive([]);

// 获取中间的项目信息
function findFeeItemVsBarCodeList() {
  feeItemList.length = 0;
  if (IsEmpty(reqMainForm.inspectCompany)) {
    return;
  }
  feeLoading.value = true;
  const url = '/lab/inspectCompFeeitem/findFeeitemListByBarCodeAndInspectCompany';
  proxy.$http
    .get(url, {
      params: {
        barcodeNo: selevctBarCodeRow.barcodeNo,
        companyCode: reqMainForm.inspectCompany
      }
    })
    .then((res: any) => {
      feeItemList.push(...res.data);
      proxy.$nextTick(() => {
        setFeeitemTableCheckBox();
      });
      feeLoading.value = false;
    })
    .catch((err: any) => {
      feeLoading.value = false;
    });
}

function feeItemChangeRow(checkedRows) {
  if (checkedRows.checked) {
    const sltFeeItem = checkedRows.row;
    const sltReqDetail = reqMainForm.labReqdetailList.filter((p) => p.feeCode === sltFeeItem.feeCode);
    if (sltReqDetail.length > 0) {
      return;
    }
    const reqDetailObj = {
      reqNo: sltReqMain.reqNo,
      feeCode: sltFeeItem.feeCode,
      feeName: sltFeeItem.feeName,
      amount: 1,
      price: sltFeeItem.price,
      costs: sltFeeItem.price,
      isCharge: 1
    };
    reqMainForm.labReqdetailList.push(reqDetailObj);
  } else {
    const sltFeeItem = checkedRows.row;
    const cnt = reqMainForm.labReqdetailList.findIndex((p: any) => p.feeCode === sltFeeItem.feeCode);
    if (cnt > -1) {
      reqMainForm.labReqdetailList.splice(cnt, 1);
    }
  }
  if (reqMainForm.labReqdetailList.length > 0) {
    reqMainForm.reqPurpose = reqMainForm.labReqdetailList.map((item: any) => item.feeName).join(',');
  } else {
    reqMainForm.reqPurpose = '';
  }
}

function saveReqMainForm() {
  //修改
  const url = '/lab/reqMain/updateReqMainAndDetail';
  let reqMainData = {} as any;
  Object.assign(reqMainData, reqMainForm);
  proxy.$http
    .post(url, reqMainData)
    .then((res: any) => {
      if (res.status.code === 1) {
        sltReqMain = res.data;
        findReqMainList();
        cancelReqMainEvent();
      } else {
        VxeMessage('新增失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      console.log(err);
      VxeMessage('新增失败', VxeNotifyType.error);
    });
}
async function deleteReqDetailList() {
  const selectRows = (proxy.$refs.labReqdetailTableRef as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请选择需要删除的项目', VxeNotifyType.warning);
    return;
  } else {
    const type = await VXETable.modal.confirm('确定删除选中记录?'); /*不能改el  $confirm 回车事件冒泡你*/
    if (type === 'confirm') {
      for (const sr of selectRows) {
        const cnt = reqMainForm.labReqdetailList.findIndex((p: any) => p.feeCode === sr.feeCode);
        if (cnt > -1) {
          reqMainForm.labReqdetailList.splice(cnt, 1);
        }
      }
      setFeeitemTableCheckBox();
      if (reqMainForm.labReqdetailList.length > 0) {
        reqMainForm.reqPurpose = reqMainForm.labReqdetailList.map((item: any) => item.feeName).join(',');
      } else {
        reqMainForm.reqPurpose = '';
      }
    }
  }
}
function setFeeitemTableCheckBox() {
  const $table = proxy.$refs.feeItemTableRef;
  if ($table) {
    $table.clearCheckboxRow();
  }
  if (reqMainForm.labReqdetailList.length > 0) {
    const sltFeeItemList = [];
    for (const redo of reqMainForm.labReqdetailList) {
      const jj = feeItemList.find((item: any) => item.feeCode == redo.feeCode);
      if (!IsEmpty(jj)) {
        sltFeeItemList.push(jj);
      }
    }
    if ($table) {
      $table.setCheckboxRow(sltFeeItemList, true);
    }
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findReqMainList();
  }
}
function companyCodeChangeEvent() {
  findReqMainList();
}
function stateCodeChangeEvent() {
  findReqMainList();
}

//#region  自定义指令
// 自定义指令
const enterNextInput: ObjectDirective<HTMLElement> = {
  mounted(el) {
    el.addEventListener('keypress', (e) => {
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      if (charcode == 13) {
        const doms: any = document.getElementsByClassName('enterNextInputFlag');
        let list = [];
        for (let i = 0; i < doms.length; i++) {
          let node = doms[i].childNodes;
          if (node.length > 0) {
            node.forEach((v) => {
              if ((v.nodeName == 'TEXTAREA' || v.nodeName == 'INPUT') && !v.disabled) {
                list.push(v);
              }
            });
          }
        }
        for (let j = 0; j <= list.length; j++) {
          if (list[j] == document.activeElement) {
            if (j == list.length - 1) {
              return;
            }
            list[j + 1].focus();
            return;
          }
        }
      }
    });
  }
};
// 使用自定义指令
proxy.$.directives = { enterNextInput: enterNextInput };
/**下拉选中行事件 */
function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    reqMainForm[r.aimKey] = e.row[r.rowKey];
  });
  const strKey = JSON.stringify(e.aimKeys);
  if (strKey.indexOf('inspectCompany') > -1) {
    findFeeItemVsBarCodeList();
  }
  //saveReqMainForm();
}

function ageChange(ageObj) {
  Object.assign(reqMainForm, ageObj);
  reqMainForm.ageStr = ageObj.age + ageObj.ageUnit;
  reqMainForm.age = ageObj.age;
  reqMainForm.ageUnit = ageObj.ageUnit;
  // saveReqMainForm();
}
</script>

<style lang="scss" scoped>
#checkapproveDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 右侧保存按钮
    .saveBtn {
      //float: right;
      margin: 0px 30px;
    }
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 机构表格
    :deep(.vxe-table--render-default) {
      height: 100%;
    }
    :deep(.vxe-table--render-wrapper) {
      height: 100%;
      background-color: $base-white;
    }
    .tableBox {
      height: calc(100% - 60px - 15px);
    }
    .tableBoBox {
      height: calc(100% - 40px);
    }

    .tableMoSaBox {
      height: calc(100% - 100px);
    }

    .searchform {
      padding: 10px 0 0 10px;

      :deep(.vxe-form--item) {
        margin-right: 30px;
      }
    }

    .searchform .vxe-input {
      --el-input-width: 120px;
    }

    .searchform .vxe-select {
      --el-select-width: 120px;
    }
    .form-input-m {
      .el-input {
        width: 150px;
      }

      .vxe-input {
        width: 150px !important;
      }
    }
  }
}
</style>
